/************************************************************************/
// Copyright (C) 2016, han_gangbiao. All rights reserved.
// Use of this source code is governed by a GPL-v2 license that can be found in the License file.
// 
// [Time]:      2016-1-4 21:53:17
// [Author]:    han_gangbiao [http://my.oschina.net/jackhen]
// [Info]:      
/************************************************************************/

#include "netbuffer.h"

net_buffer_row_t::net_buffer_row_t()
{
	m_fd = INVALID_SOCKET_FD;
	memset(m_ip, 0, sizeof(m_ip));
	m_port = 0;
}

net_buffer_pool_t::net_buffer_pool_t()
{
	m_threshold = 10000;
}

net_buffer_pool_t::~net_buffer_pool_t()
{

}

void net_buffer_pool_t::set_pool_threshold( int threshold )
{
	smart::guard_t guard(&m_lock);
	m_threshold = threshold;
}

smart::ref_ptr<net_buffer_row_t> net_buffer_pool_t::create_buffer_row()
{
	smart::ref_ptr<net_buffer_row_t> row = NULL;
	m_lock.lock();
	if(m_buffer_pool.size() == 0)
	{
		row = new net_buffer_row_t();
	}
	else
	{
		row = m_buffer_pool.front();
		m_buffer_pool.pop_front();
	}
	m_lock.unlock();
	return row;
}

int net_buffer_pool_t::recycle( smart::ref_ptr<net_buffer_row_t>& ref_row )
{
	if(ref_row == NULL)
		return -1;
	m_lock.lock();
	if(m_buffer_pool.size() <= (unsigned int)m_threshold && ref_row->m_data.capacity() <= MAX_BUFFER_BLOCK)
	{
		m_buffer_pool.push_back(ref_row);
	}
	m_lock.unlock();
	ref_row = NULL; //must assign NULL, avoid to use ref_row again.
	return 0;
}
